package org.alala.user.common.dao.user.impl;

import java.util.List;

import org.alala.datamodels.common.query.Query;
import org.alala.datamodels.common.query.QueryItem;
import org.alala.user.common.dao.mysql.MysqlDaoBase;
import org.alala.user.common.dao.user.UserDao;
import org.alala.user.data.models.User;
import org.alala.user.data.models.util.DateUtil;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends MysqlDaoBase implements UserDao {
	
	@Override
	public String namespace() {
		return "models.user";
	}
	
	@Override
	public List<User> gets(int page, int pageSize) {
		Query query = new Query();
		query.setOffset(page * pageSize);
		query.setLimit((page + 1) * pageSize);
		
		List<User> users = super.selectList("find", query);
		for(User user : users) {
			this.adjust(user);
		}
		
		return users;
	}

	@Override
	public User get(int id) {
		User user = super.selectOne("findOne", Query.newQueryWithId(id));
		this.adjust(user);
		return user;
	}

	@Override
	public int add(User user) {
		return super.insert("insertSelective", user);
	}
	
	private void adjust(User user) {
		if(user.getBirth() != null) {
			user.setAge(DateUtil.getAgeByBirthday(user.getBirth()));
		}
	}

	@Override
	public List<User> search(String name) {

		Query query = new Query();
		query.addQueryItem(QueryItem.newString("name").contains(name));
		
		return super.selectList("find", query);
	}
}
